package com.fanfan.shiroadmin.modules.sys.service.impl;

import com.fanfan.shiroadmin.common.exception.ServiceRuntimeException;
import com.fanfan.shiroadmin.modules.sys.dao.SysMenuMapper;
import com.fanfan.shiroadmin.modules.sys.entity.SysMenuEntity;
import com.fanfan.shiroadmin.modules.sys.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author DunFan.Liao
 * @date 2022/1/2 14:17
 */
@Service(ISysMenuService.BEAN_ID)
public class SysMenuServiceImpl implements ISysMenuService
{

    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Override
    public List<SysMenuEntity> queryMenuList() throws ServiceRuntimeException
    {
        List<SysMenuEntity> all = sysMenuMapper.selectList(null);
        return all.stream()
                .filter(menuEntity -> menuEntity.getMenuLvl() == 0)
                .peek(menuEntity -> menuEntity.setChild(getChild(all, menuEntity)))
                .sorted(Comparator.comparingInt(SysMenuEntity::getMenuOrd))
                .collect(Collectors.toList());
    }

    private List<SysMenuEntity> getChild(List<SysMenuEntity> all,SysMenuEntity menu)
    {
        return all.stream()
                .filter(menuEntity -> menuEntity.getParentId() == menu.getId())
                .peek(menuEntity -> menuEntity.setChild(getChild(all,menuEntity)))
                .sorted(Comparator.comparingInt(SysMenuEntity::getMenuOrd))
                .collect(Collectors.toList());
    }
}
